package service;

import java.io.IOException;

import main.DataTransferObject;

import com.maxmind.geoip.Location;
import com.maxmind.geoip.LookupService;
import com.maxmind.geoip.regionName;
import com.maxmind.geoip.timeZone;

public class LocationService {

	/**
	 * Gets the location details of a given IP address.
	 * 
	 * @param ip - in the form of "255.255.255.255"
	 * @return DTO with fill in location data
	 */
	public static DataTransferObject getLocationDetails(String ip) {
		DataTransferObject locDTO = new DataTransferObject();
		try {
			LookupService ls = new LookupService("lib/GeoLiteCity.dat",
					LookupService.GEOIP_MEMORY_CACHE);
			Location loc = ls.getLocation(ip);

			locDTO.setIp(ip);
			locDTO.setCountry(loc.countryName);
			locDTO.setCity(loc.city);
			locDTO.setAreaCode(String.valueOf(loc.area_code));
			
			ls.close();
		} catch (IOException e) {
			System.out.println("IO Exception");
		}
		return locDTO;
	}
	
	/**
	 * Gets the location details of a given IP address.
	 * 
	 * @param inDTO - in the form of "255.255.255.255"
	 * @return DTO with fill in location data
	 */
	public static DataTransferObject getLocationDetails(DataTransferObject inDTO) {
		DataTransferObject locDTO = new DataTransferObject();
		try {
			LookupService ls = new LookupService("lib/GeoLiteCity.dat",
					LookupService.GEOIP_MEMORY_CACHE);
			Location loc = ls.getLocation(inDTO.getIp());

			locDTO.setCountry(loc.countryName);
			locDTO.setCity(loc.city);
			locDTO.setAreaCode(String.valueOf(loc.area_code));
			
			ls.close();
		} catch (IOException e) {
			System.out.println("IO Exception");
		}
		return locDTO;
	}
}
